package beans.impl;

import beans.CartLocal;
import beans.Product;
import beans.Account;
import exception.CartException;
import java.util.ArrayList;
import javax.persistence.EntityManager;

/**
 * Caddie virtuel
 * @author M2 MIAGE Apprentissage - Groupe 3 (VAlbiser)
 */
public class CartBean implements java.io.Serializable, CartLocal {

    EntityManager entityManager;

    private Account account;
    private ArrayList<Product> productList;
    private String status;

    public CartBean() {}

    public CartBean(AccountBean account){
        this.account = account;
        this.productList = new ArrayList<Product>();
        this.status = "EMPTY";
    }

    public ArrayList getProductList() {
        return productList;
    }
    public void setProductList(ArrayList productList) {
        this.productList = productList;
    }

    public boolean isEmpty() {
        return this.status.equalsIgnoreCase("EMPTY");
    }

    public boolean isFilling() {
        return this.status.equalsIgnoreCase("FILLING");
    }

    public boolean isBought() {
        return this.status.equalsIgnoreCase("BOUGHT");
    }

    public void setStatus(String status) {
        this.status = status;
    }
        
    public void addProduct(String productId) throws CartException {

        if(this.isBought()) throw new CartException("Caddy déjà payé");

        Product p =  entityManager.find(ProductBean.class, productId);
        productList.add(p);
        status = "FILLING";
    }

    public ArrayList getProducts() {
        return productList;
    }

    public double getTotalPrice() {
        double total=0;

        for(Product prod : productList) {
            total += prod.getPrice();
        }
        
        return total;
    }

    public void buy() throws CartException {
        if(this.isEmpty()) throw new CartException("Votre caddy est vide");
        if(account.getBalance() > this.getTotalPrice()) {
            account.withdraw(this.getTotalPrice());
            this.status = "BOUGHT";
        } else {
            throw new CartException("Fonds Insuffisants !");
        }
    }

}
